package com.admin.system.runner;

import com.admin.common.entity.CaptchaParamConfigBO;
import com.admin.core.dto.cache.FileParamConfigBO;
import com.admin.core.dto.cache.LoginParamConfigBO;
import com.admin.core.dto.cache.ParamConfigCacheBO;
import com.admin.core.entity.SysParamConfig;
import com.admin.system.modules.system.service.ParamConfigService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author /
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ParamConfigRunner implements ApplicationRunner {

    private final ParamConfigService paramConfigService;

    /**
     * @param applicationArguments /
     */
    @Override
    public void run(ApplicationArguments applicationArguments) {
        ParamConfigCacheBO.list = paramConfigService.list();

        ParamConfigCacheBO.loginParamConfig = handle("login.", LoginParamConfigBO.class);
        ParamConfigCacheBO.captchaParamConfig = handle("captcha.", CaptchaParamConfigBO.class);
        ParamConfigCacheBO.fileParamConfig = handle("file.", FileParamConfigBO.class);
    }

    <T> T handle(String prefix, Class<T> clazz) {
        JSONObject jsonObject = new JSONObject();
        for (SysParamConfig entry : ParamConfigCacheBO.list) {
            if (entry.getCode().startsWith(prefix)) {
                String attr = entry.getCode().substring(prefix.length());
                jsonObject.put(attr, entry.getValue());
            }
        }
        return JSON.toJavaObject(jsonObject, clazz);
    }
}
